package com.alit.face.koala.service.subject;

import java.util.Optional;

import org.apache.commons.codec.binary.Base64;
import org.json.JSONException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alit.face.koala.entity.BaiduFaceDetecteResult;
import com.alit.face.koala.entity.UploadFileEntity;
import com.alit.face.koala.repository.BaiduFaceDetecteResultRepository;
import com.alit.face.koala.service.face.baidu.BaiduFaceService;
import com.alit.face.koala.util.JsonUtil;

import lombok.extern.slf4j.Slf4j;

@Slf4j
@Service
public class BaiduFaceDetecteService {
  @Autowired
  private BaiduFaceService baiduFaceService;
  @Autowired
  private BaiduFaceDetecteResultRepository baiduFaceDetecteResultRepository;

  /**
   * 人脸检测
   * 1.查询本地库,如果本地库没有数据,百度,并经数据保存到本地库 
   */
  public org.json.JSONObject detected(UploadFileEntity upload) {
    // 查询数据库中的人脸检测结果
    Optional<BaiduFaceDetecteResult> optional = baiduFaceDetecteResultRepository.findById(upload.getMd5());
    BaiduFaceDetecteResult entity = null;
    org.json.JSONObject detectedResult = null;

    if (optional.isPresent()) {
      entity = optional.get();
      String string = entity.getResult();
      log.info("从数据库中获取到人脸检测结果" + string);
      detectedResult = JsonUtil.parseJsonObject(string);
    } else {
      // 数据库中不存在face token,进行人脸检测
      // 上传文件,人脸检测
      String encodeBase64String = Base64.encodeBase64String(upload.getBytes());
      detectedResult = baiduFaceService.detected(encodeBase64String);
      int errorCode = -1;
      try {
        errorCode = detectedResult.getInt("error_code");
        if (errorCode != 0) {
          log.info("图片检测出现问题:" + detectedResult);
          return detectedResult;
        }
      } catch (JSONException e) {
        log.error("获取图片检测检测错误码异常:" + e.getMessage());
        return detectedResult;
      }
      log.info("人脸检测结果:" + detectedResult.toString());
      // 将信息保存到数据库
      entity = new BaiduFaceDetecteResult();
      entity.setMd5(upload.getMd5());
      entity.setResult(detectedResult.toString());
      baiduFaceDetecteResultRepository.save(entity);
    }
    return detectedResult;
  }

}
